package com.example.demo.controller;


import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Article;
import com.example.demo.model.User;
import com.example.demo.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;

    /**
     * 获取帖子列表
     * @param boardId 板块Id
     * @return AppResult<List<Article>>
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块Id") @RequestParam(value = "boardId",required = false) Long boardId){

        //定义要返回的结果
        List<Article> results;
        if(boardId == null){
            //1.boardId为空时，获取所有的帖子
            results = articleService.selectAll();
        }else{
            //2.boardId不为空时，获取指定板块下的帖子
            results = articleService.selectByBoardId(boardId);
        }
        //防止返回的结果是null
        if(results == null){
            results = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(results);
    }

    /**
     * 根据用户Id查询帖子列表
     *
     * @param userId 用户Id
     * @return 指定版块的帖子列表
     */
    @ApiOperation("根据用户Id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam(value = "用户Id") @RequestParam(value = "userId", required = false) Long userId) {

        // 根据参数中的userId是否为空决定返回哪个用户的帖子列表
        // 1. userId 为空，获取当前登录用户Id
        // 2. userId 不为空，指定id的用户
        if (userId == null) {
            // 获取Session中的用户信息
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
            // 获取当前登录用户的Id
            userId = user.getId();
        }
        // 查询用户的帖子列表
        List<Article> result = articleService.selectByUserId(userId);
        log.info("查询用户帖子列表, userId = " + userId);
        // 返回结果
        return AppResult.success(result);
    }

    /**
     * 发布帖子
     * @param boardId 板块Id
     * @param title 标题
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("内容") @RequestParam("content") @NonNull String content){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //判断用户状态
        if(user.getState() == 1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //构造帖子对象
        Article article = new Article();
        article.setUserId(user.getId());//作者Id
        article.setBoardId(boardId);//板块Id
        article.setTitle(title);//标题
        article.setContent(content);//内容
        //调用Service
        articleService.create(article);
        //返回结果
        return AppResult.success("发布成功");
    }


    @ApiOperation("获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //调用Service
        Article article = articleService.selectDetailsById(id);
        //判断当前登录用户是不是帖子的作者
        if(user.getId() == article.getUserId()){
            //设置所有者标识为true
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    @ApiOperation("更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){
        //1.校验用户状态，禁言状态不能更新
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if(user.getState() == 1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.查询帖子详情
        Article article = articleService.selectDetailsById(id);
        //3.校验帖子状态，是否删除，是否封贴
        if(article == null || article.getDeleteState() == 1){
            //帖子不存在或已删除返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4.校验当前登录用户是不是帖子的作者
        if(user.getId() != article.getUserId()){
            //返回错误信息的描述
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用Service
        articleService.modify(id,title,content);
        //返回结果
        return AppResult.success();
    }

    /**
     * 点赞
     *
     * @param id 帖子Id
     * @return AppResult
     */
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam(value = "帖子Id") @RequestParam(value = "id") @NonNull Long id) {
        // 获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 判断是否被禁言
        if (user.getState() != 0) {
            // 日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 更新点赞数
        articleService.thumbsUpById(id);

        // 返回结果
        return AppResult.success();
    }

    /**
     * 根据Id删除帖子
     *
     * @param id 帖子Id
     * @return
     */
    @ApiOperation("根据Id删除帖子")
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam(value = "帖子Id") @RequestParam(value = "id") @NonNull Long id) {
        // 获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 调用Service层获取帖子详情
        Article result = articleService.selectById(id);
        // 当前用户是否作者
        if (result == null || user.getId() != result.getUserId()) {
            // 日志
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 调用删除方法
        articleService.deleteById(result.getId());
        // 返回结果
        return AppResult.success();
    }
}
